package com.itboy.message.controller;

import com.itboy.common.core.domain.AjaxResult;
import com.itboy.message.config.WxAutoConfiguration;
import com.itboy.message.domain.WeChatMessage;
import com.itboy.message.properties.WeChatMessageProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/message")
@Slf4j
public class MessageController {

    @Autowired
    private WeChatMessageProperties weChatMessageProperties;

    @Autowired
    private WxAutoConfiguration wxAutoConfiguration;

    @Autowired
    private RestTemplate restTemplate;


    @RequestMapping("wxSend")
    public AjaxResult<String> wxSend(String openId,String name){
        openId="oImQJ6waX7LZizKVoOcGKDAt4FBM";
        name="song";
        Map<String,Map<String,Object>> map=new HashMap<>();
        WeChatMessage weChatMessage = new WeChatMessage();
        weChatMessage.setToUser(openId);
        weChatMessage.setUrl("https://www.baidu.com");
        weChatMessage.setTemplateId(weChatMessageProperties.getTemplateId());
        weChatMessage.setTopColor("#ff0000");

        map.put("userName",WeChatMessage.buildMap(name,"#ff0000"));
        map.put("time",WeChatMessage.buildMap(LocalDateTime.now().toString(),"#ff0000"));
        weChatMessage.setData(map);
        String result=null;
        try {
            //微信access_token
            String wxAccessToken = wxAutoConfiguration.getWxAccessToken();
            //发送消息地址
            String sendMsgUrl = weChatMessageProperties.getSendMsgUrl();
            //将地址入参
            String realSendUrl = String.format(sendMsgUrl, wxAccessToken);
            result = restTemplate.postForObject(realSendUrl, weChatMessage, String.class);
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
            log.error("发送公众号消息失败");
        }

        return AjaxResult.success("发送成功",result);


    }
}
